package com.example.service.impl;

import com.example.Pojo.Dept;
import com.example.Pojo.DeptLog;
import com.example.mapper.DeptMapper;
import com.example.mapper.EmpMapper;
import com.example.service.DeptLogService;
import com.example.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    //这里不能直接操作数据库信息
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;


    //@MyLog
    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }


    //根据id删除部门信息
    @Transactional(rollbackFor = Exception.class)//spring事务管理
    //如果想要所有的异常都出现回滚 那么需要在@Transactional(rollbackFor = Exception.class)
    //写上rollbackFor,然后给的值是最大的异常 这样就行了

    //目前在service层添加
    @Override
    public void delete(Integer id) throws Exception {
        try {
            deptMapper.deleteById(id);
            /*if (true){
                throw new Exception("出错啦...");
            }*/
            empMapper.deleteByDeptId(id);
        } finally {
            //操作日志输出,利用try...finally,不管是否执行成功日志都会输出
            DeptLog depLog = new DeptLog();
            depLog.setCreateTime(LocalDateTime.now());
            depLog.setDescription("当前执行删除id为:" + id + "的部门操作");
            deptLogService.insert(depLog);
        }
    }

    //新增部门信息
    @Override
    public void insert(Dept dept) {
        //在这里直接修改时间信息
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insertDept(dept);
    }

    //修改部门信息
    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }

    //根据id查询部门信息
    @Override
    public Dept selectOne(Integer id) {
        return deptMapper.selcetDept(id);
    }
}
